import net from 'net'

var listenStatus = 0
var targetHosts = [];
var mainWin = null;
const listenTCP = (win, ipcMain) => {
    mainWin = win;


    function getContentAroundColon(str) {
        const parts = str.split(':'); // 使用 ':' 来分割字符串
        if (parts.length === 2) {
            const beforeColon = parts[0];  // 获取 ':' 前的部分
            const afterColon = parts[1];   // 获取 ':' 后的部分
            return { host: beforeColon, port: afterColon };
        } else {
            return { host: '', port: '' };  // 如果没有 ':' 或多个 ':'，返回空字符串
        }
    }

    // 异步函数：检查目标的连接延迟
    function checkLatency(url) {
        return new Promise((resolve, reject) => {
            const startTime = Date.now();  // 记录连接开始的时间
            let { host, port } = getContentAroundColon(url)

            // 创建到目标地址的连接
            const client = net.createConnection({ host, port }, () => {
                const endTime = Date.now();
                const latency = endTime - startTime;  // 计算延迟时间
                client.end();  // 关闭连接
                resolve(latency);
            });

            // 连接错误处理
            client.on('error', (err) => {
                reject(err);  // 执行reject表示该连接出错
            });
        });
    }




    // 实时监听每个目标的连接延迟
    function startRealTimeMonitoring() {
        targetHosts.forEach((item) => {
            // 每5秒钟检查一次延迟
            setInterval(async () => {
                try {
                    const latency = await checkLatency(item.url);  // 获取延迟
                    item.speed = latency;
                    mainWin.webContents.send("IP-speed", targetHosts);

                } catch (error) {
                    item.speed = -1
                    mainWin.webContents.send("IP-speed", targetHosts);
                }
            }, 5000);  // 5秒钟一次
        });
    }

    ipcMain.on("listentcp", (event, text) => {
        if (listenStatus == 0) {
            listenStatus = 1
            targetHosts = JSON.parse(text)
            if (targetHosts.length > 0) {
                // 启动实时监听
                startRealTimeMonitoring();
            }
        }


    })

};

export default listenTCP;
